import option from "../option.json" with { type: "json" }
import puppeteer from "puppeteer"

function throwFerchError(res, action) {
    let reason = res.reason
    if (typeof reason === 'object') {
        reason = JSON.stringify(reason)
    }
    throw new Error(action + ": " + (reason || JSON.stringify(res)))
}

async function frpFetch(url, body) {
    const res = await fetch(url, {
        method: "POST",
        body: JSON.stringify({
            ...body,
            session: option.session,
        }),
    })
    return await res.json()
}

async function getProductionOrderList(orderId) {
    const res = await frpFetch(option.api.getDataMap, {
        tableNames: ["productionOrder"],
        filter: {
            productionOrder: `orderId = ${orderId}`,
        },
        column: {
            productionOrder: ["_id", "code", 'oldCode', 'totalNum', 'styleCode', 'status', 'planStartDate', 'planEndDate', 'j_FID', 'deliverType'],
        },
    })
    if (res.code !== 200) {
        throw new Error(res.reason || JSON.stringify(res))
    }
    return res.data.productionOrder
}

async function getOrderId(orderCode) {
    const res = await frpFetch(option.api.getDataMap, {
        tableNames: ["order"],
        filter: {
            order: `code = "${orderCode}"`,
        },
        column: {
            order: ["_id"],
        },
    })

    if (res.code !== 200) {
        throw new Error(res.reason || JSON.stringify(res))
    }
    if (!res.data.order[0]?.["数据ID"]) {
        throw new Error("未找到orderCode对应order")
    }

    return res.data.order[0]["数据ID"]
}

async function getFRPPage(url) {
    const browser = await puppeteer.launch({ headless: false, devtools: false })
    const page = await browser.newPage()

    page.on("response", async (res) => {
        const headers = res.headers()
        if (headers["content-type"] !== "application/json") {
            return
        }
        const data = await res.json()
        if (!(data.code === 200 || data.isSuccess)) {
            console.log(res.url())
            return new Error(data.reason || JSON.stringify(data))
        }
    })

    await page.goto(url)
    await page.setViewport({ width: 1240, height: 720 })
    await page.evaluate((frpOption) => {
        // eslint-disable-next-line no-undef
        sessionStorage.session = frpOption.session
    }, option)
    await page.waitForNetworkIdle()

    return { browser, page }
}

async function setErrorLog(orderCode, oldCode, errMsg) {
    const res = await fetch(option.api.logError, {
        method: "POST",
        body: JSON.stringify({
            orderCode, oldCode, errMsg
        }),
    })
    return await res.json()
}

export { frpFetch, getFRPPage, getOrderId, throwFerchError, getProductionOrderList, setErrorLog }
